package com.bangyo.common.spider.impl;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;

import com.bangyo.common.spider.Spider;
import com.bangyo.stuff.Text;

public class TwitterUserTimelineSpider implements Spider<List<Text>>
{

    public List<Text> spy(String url) throws IOException
    {
        String jsonString = IOUtils.toString(new URL(url).openStream());
        if (null==jsonString)
            return Collections.emptyList();
        JSONArray timelines = JSONArray.fromObject(jsonString);
        List<Text> textList = new ArrayList<Text>(timelines.size());
        for (int i = 0; i<timelines.size(); i++)
        {
            JSONObject timeline = timelines.getJSONObject(i);
            Text text = new Text();
            text.setTitle(timeline.getString("text"));
            textList.add(text);
        }
        return textList;
    }

    public static void main(String[] args) throws IOException
    {
        TwitterUserTimelineSpider spider = new TwitterUserTimelineSpider();
        List<Text> links = spider
            .spy("http://twitter.com/statuses/user_timeline/zkyo.json");
        for (Text link:links)
        {
            System.out.println(link.getTitle());
        }
    }
}
